package com.duowan.realtime.uniq.algorithm.bloomfilter.util;

import java.io.File;
import java.io.IOException;
import java.util.BitSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duowan.datawarehouse.util.FileUtil;
import com.duowan.realtime.server.util.ExpandFileUtils;
import com.duowan.realtime.thrift.PartitionedBloomFilter;
import com.duowan.realtime.uniq.algorithm.bloomfilter.BloomFilter;

public class BFFileHelper {
	
	
	private static final Logger LOG  = LoggerFactory.getLogger(BFFileHelper.class);

	private static final String backupBaseDir = "/data/backup/bloomfilter";
	
	public static void downToBackupFiles(String subFilePath, String fileName, BloomFilter bloomFilter){
		//delete the subFilePath before down
		String parentDir = backupBaseDir+ "/" + subFilePath;
		deleteFileByParentDir(parentDir);
		File file = new File(parentDir + "/" + fileName);
		try {
			ExpandFileUtils.writeObjectToFile(file, bloomFilter);
		} catch (IOException e) {
			LOG.error("excute ExpandFileUtils.writeObjectToFile error", e);
		}
	}

	public static void deleteFileByParentDir(String subFilePathDir) {
		List<File> fileList = FileUtil.listFiles(subFilePathDir);
		for (File file : fileList) {
			file.delete();
		}
	}
	
	public static void deleteFile(String filePrefix){
		List<File> backupFiles = FileUtil.listFiles(backupBaseDir);
		for (File file : backupFiles) {
			if (file.getName().startsWith(filePrefix)) {
				file.delete();
			}
		}
	}

	public static BloomFilter loadFromBackupFiles(String bloomfilterPath, String fileName) {
		File file = new File(bloomfilterPath + "/" + fileName);
		BloomFilter bloomFilter = null;
		if (file.exists()) {
			try {
				bloomFilter = (BloomFilter)ExpandFileUtils.readObjectFromFile(file);
				LOG.info("load backup bloomfilter : " + file.getName());
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				LOG.error("reload backup bloomfilter IOException :", e);
			}
		}
		return bloomFilter;
	}
}
